﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Charades.Web.Helpers;
using Charades.Web.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace Charades.Web.Server.User
{
	public class UserHandler
	{
		private ConcurrentDictionary<string, User> _userList;

		public UserHandler()
		{
			_userList = new ConcurrentDictionary<string, User>();
			UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
		}

		public UserManager<ApplicationUser> UserManager { get; private set; }

		public void AddUser(User user)
		{
			_userList.TryAdd(user.ConnectionId, user);
            ElmahLogger.LogMessage(String.Format(
                "{0} вошел.", user.Name));
		}

		public void RemoveUser(string connectionId)
		{
			User u;
			_userList.TryRemove(connectionId, out u);
		}

		public User GetUser(string connectionId)
		{
			return _userList.ContainsKey(connectionId) ? _userList[connectionId] : null;
		}

		public List<User> GetUsers()
		{
			return _userList.Values.ToList();
		}

		public int GetUsersCount()
		{
			return _userList.Values.Count;
		}

		public ICollection<string> GetUserConnectionIds()
		{
			return _userList.Keys;
		}

		public bool UserExists(string connectionId)
		{
			return _userList.ContainsKey(connectionId);
		}

		public bool IsBanned(string connectionId)
		{
			var user = GetUser(connectionId);
			if (user != null)
			{
				var identity = UserManager.FindByName(HttpUtility.HtmlDecode(user.Id));
				if (identity != null)
				{
					return identity.WasBanned.HasValue && (DateTime.UtcNow - identity.WasBanned.Value).Hours < 2;
				}
			}

			return false;
		}
	}
}